﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Web;

namespace ConsoleApplication1.Submitters
{
    class SPOJSubmitter : Submitter
    {
        // constructor
        public SPOJSubmitter(){
            used[0] = used[1] = false;
            submission = new Submission();
        }

        private int getIdleClient()
        {
            for (int i = 0; i < MaxUsernames; i++)
            {
                if (!used[i]) return i;
            }
            return -1;
        }

        private void getResult(int idx)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            long cur = sw.ElapsedMilliseconds;
            int sleepInterval = 2000;

            httpRequest[idx].Method = "GET";

            while (sw.ElapsedMilliseconds - cur < 15000)
            {
                httpRequest[idx] = (HttpWebRequest)WebRequest.Create("http://www.spoj.pl/status/montano");
                HttpWebResponse response = (HttpWebResponse)httpRequest[idx].GetResponse();

                Stream dataStream = response.GetResponseStream();

                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);

                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                StreamWriter file = new StreamWriter("status.txt");
                file.WriteLine(responseFromServer);
                file.Close();

                int p = responseFromServer.IndexOf("max_id") + 15;
                int cid = 0;
                while (Char.IsDigit(responseFromServer[p]))
                {
                    cid = 10 * cid + (int)responseFromServer[p] - (int)'0';
                    p++;
                }

                p = responseFromServer.IndexOf("id=\"statusres_" + cid +"\"");
                while (responseFromServer[p] != '>') p++;
                p++;
                string result = "";
                while (responseFromServer[p] != '<')
                {
                    result += responseFromServer[p];
                    p++;
                }

                result = result.Trim();
                submission.status = result;

                if (!result.Contains("ing"))
                {
                    return;
                }

                TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, sleepInterval);
                Thread.Sleep(timeSpan);
            }
            sw.Stop();
        }

        private void work()
        {
            int idx = getIdleClient();
            used[idx] = true;

            httpRequest[idx] = (HttpWebRequest)WebRequest.Create("http://www.spoj.pl/submit/complete/");
            httpRequest[idx].Method = "POST";

            StreamReader sourcereader = new StreamReader("source.cpp");
            string source = sourcereader.ReadToEnd();
            source = HttpUtility.UrlEncode(source);

            string[] data = { "lang=41", "file=" + source, "problemcode=TEST", "submit=Send", "login_user=montano", "password=montanovpass" };
            string postData = data[0];

            for (int i = 1; i < data.Length; i++)
            {
                postData += "&" + data[i];
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            httpRequest[idx].ContentType = "application/x-www-form-urlencoded";
            httpRequest[idx].ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = httpRequest[idx].GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            // Get the response.
            CookieContainer CC = new CookieContainer();
            httpRequest[idx].CookieContainer = CC;
            HttpWebResponse response = (HttpWebResponse)httpRequest[idx].GetResponse();
            getResult(idx);

            StreamWriter sr = new StreamWriter("result.txt");
            sr.WriteLine(submission.status);
            sr.Close();

            used[idx] = false;
        }

        protected override void run()
        {
            work();
        }

        public void submit()
        {
            Thread thread = new Thread(new ThreadStart(this.run));
            thread.Start();
        }
    }
}
